package com.unknow.first.dapp.admin.account.service.impl;

import com.unknow.first.dapp.admin.account.constants.ITradeTypeEnum;
import com.unknow.first.dapp.admin.account.service.TradeTypeService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

@Component
public class TradeTypeServiceImpl implements TradeTypeService {

    private final List<ITradeTypeEnum> tradeTypeList = new ArrayList<>();

    @SneakyThrows
    @Lazy
    public TradeTypeServiceImpl() {

        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(ITradeTypeEnum.class));

        Set<BeanDefinition> components = provider.findCandidateComponents("com.unknow.first.dapp.admin.account.constants");
        for (BeanDefinition component : components) {
            Class<? extends ITradeTypeEnum> cls = (Class<? extends ITradeTypeEnum>) Class.forName(component.getBeanClassName());

            ITradeTypeEnum[] tradeTypeEnum = cls.getEnumConstants();
            if (tradeTypeEnum == null) {
                return;
            }
            for (ITradeTypeEnum iTradeTypeEnum : tradeTypeEnum) {
                tradeTypeList.add(new ITradeTypeEnum() {
                    @Override
                    public int getValue() {
                        return iTradeTypeEnum.getValue();
                    }

                    @Override
                    public String getName() {
                        return iTradeTypeEnum.getName();
                    }

                    @Override
                    public String getI18nValue() {
                        return iTradeTypeEnum.getI18nValue();
                    }

                    @Override
                    public boolean isShow() {
                        return iTradeTypeEnum.isShow();
                    }
                });
            }

            tradeTypeList.sort(Comparator.comparingInt(ITradeTypeEnum::getValue));
        }


//        Reflections reflections = new Reflections("com.unknow.first.dapp.admin.account.constants");
//        Set<Class<? extends ITradeTypeEnum>> tradeTypeEnumSubTypes = reflections.getSubTypesOf(ITradeTypeEnum.class);
//        tradeTypeEnumSubTypes.forEach(cls -> {


//        });

    }

    @Override
    public List<ITradeTypeEnum> listTradeType() {
        return tradeTypeList;
    }
}
